package com.relife.sys.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

import com.relife.common.exception.BusinessException;
import com.relife.common.model.Client;
import com.relife.common.model.ClientManager;
import com.relife.common.security.DESUtil;
import com.relife.common.utils.ReflectUtil;
import com.relife.common.utils.StringUtil;
import com.relife.common.utils.SysConfig;
import com.relife.core.entity.*;
import com.relife.core.qbc.QbcQuery;
import com.relife.core.service.BaseService;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service
@Transactional
public class AdminService extends BaseService {

	/**
	 * 用户登录验证
	 * 
	 * @author WU
	 * @date 2016年5月9日 下午4:24:16
	 * @param userName
	 * @param pwd
	 * @param client
	 */
	public void login(String userName, String pwd, Client client) {
		Criteria crit = this.createCriteria(UserEntity.class);
		crit.add(Restrictions.eq("state", 0));
		crit.add(Restrictions.eq(StringUtil.isPhone(userName) ? "phone" : "userName", userName));
		UserEntity user = (UserEntity) crit.uniqueResult();
		if (user == null) {
			throw new BusinessException("用户不存在!");
		}
		if (!user.getPassword().equals(DESUtil.encrypt(pwd, SysConfig.PWD_KEY))) {
			throw new BusinessException("密码错误!");
		}

		if (user.getDepartUser() != null) {
			for (DepartUserEntity du : user.getDepartUser()) {
				du.getDepart().getName();// lazy
				if (du.getDepart().getParent() != null) {
					du.getDepart().getParent().getName();// lazy
				}
				client.getDepartList().add(du.getDepart());
			}
		}
		client.setUser(user);
		client.setDepartSize(user.getDepartUser().size());
		if (client.getDepartSize() == 0) {
			throw new BusinessException("组织机构未配置，请于管理员联系。");

		}
		if (client.getDepartSize() == 1) {
			client.setDepart(client.getDepartList().get(0));
			getClient(client);
		}
	}

	/**
	 * 获取登录用户 角色、菜单权限，
	 * 
	 * @author WU
	 * @date 2016年5月9日 下午4:26:46
	 * @param client
	 */
	public void getClient(Client client) {
		client.clear();
		String derpartCode = client.getDepart().getDepartCode().substring(0, 3);
		int level = client.getDepart().getDepartCode().length() / 3;
		// 集团
		if (level == 1) {
			client.setCompany(client.getDepart());

		} else if (level == 2) {
			// 部门或组
			if (client.getDepart().getType() > 2) {
				client.setCompany(get(DepartmentEntity.class, "departCode", derpartCode));
			} else {// 公司
				client.setCompany(client.getDepart());
			}
		} else {
			String depCode = client.getDepart().getDepartCode();
			// 分公司
			if (client.getDepart().getDepartCode().contains("C")) {
				depCode = depCode.substring(0, 9);
			} else {
				depCode = depCode.substring(0, 6);
			}
			client.setCompany(get(DepartmentEntity.class, "departCode", depCode));
		}

		QbcQuery qbc = new QbcQuery(UserRoleEntity.class);
		qbc.createAlias("role", JoinType.INNER_JOIN);
		qbc.add(Restrictions.eq("user.id", client.getUser().getId()));
		qbc.add(Restrictions.eq("depart.id", client.getDepart().getId()));
		List<UserRoleEntity> urList = this.getList(qbc);

		if (client.getUser().isAdmin()) {
			List<FunctionEntity> butList = this.getList(FunctionEntity.class, "type", 2);
			for (int i = 0; i < butList.size(); i++) {
				client.getButMap().put(butList.get(i).getCode(), butList.get(i));
			}
			QbcQuery fQbc = new QbcQuery(FunctionEntity.class);
			fQbc.add(Restrictions.ne("type", 2));
			List<FunctionEntity> funList = this.getList(fQbc);
			client.setfList(funList);

		} else {

			List<FunctionEntity> flist = new ArrayList<FunctionEntity>();
			List<RolePermissionEntity> rpList = new ArrayList<RolePermissionEntity>();
			if (urList != null) {
				for (int i = 0; i < urList.size(); i++) {
					client.getRoleList().add(urList.get(i).getRole());
					client.getHomeSetList().addAll(urList.get(i).getRole().getHomeSetList());
					flist.addAll(urList.get(i).getRole().getFunctionList());
					rpList.addAll(urList.get(i).getRole().getRolePerList());
				}

				// list去重复
				HashSet<FunctionEntity> set = new HashSet<FunctionEntity>();
				set.addAll(flist);
				client.getfList().addAll(set);
			}

			for (int i = client.getfList().size() - 1; i >= 0; i--) {
				if (client.getfList().get(i).getType().intValue() == 2) {
					client.getButMap().put(client.getfList().get(i).getCode(), client.getfList().get(i));
					client.getfList().remove(i);
				}
			}

			List<PermissionEntity> pList = new ArrayList<PermissionEntity>();
			for (int i = 0; i < rpList.size(); i++) {
				if (rpList.get(i).getPermission() != null) {
					rpList.get(i).getPermission().getName();// lazy
					pList.add(rpList.get(i).getPermission());
				}
			}

			// list去重复
			HashSet<PermissionEntity> pSet = new HashSet<PermissionEntity>();
			pSet.addAll(pList);
			client.getPreList().addAll(pSet);
		}

		// list排序
		ComparatorUser c = new ComparatorUser();
		Collections.sort(client.getfList(), c);
	}

	/**
	 * 修改用户消息
	 * 
	 * @author WU
	 * @date 2016年5月9日 下午4:24:29
	 * @param user
	 */
	public void saveOrUpdateUser(UserEntity user) {
		this.checkUser(user);
		if (user.getId() == null) {
			user.setPassword(DESUtil.encrypt("123456", SysConfig.PWD_KEY));
			this.save(user);
			user.setUserCode(user.getId());
		} else {
			UserEntity us = this.get(UserEntity.class, user.getId());
			ReflectUtil.copyNotNullPro2Bean(user, us);
		}
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年5月30日 下午4:35:31
	 * @param oldPwd
	 * @param pwd
	 * @param newPwd
	 */
	public void updatePwd(String oldPwd, String pwd, String newPwd) {
		String userId = ClientManager.getInstance().getClientSession().getUser().getId();
		UserEntity user = this.get(UserEntity.class, userId);
		if (!DESUtil.encrypt(oldPwd, SysConfig.PWD_KEY).equals(user.getPassword())) {
			throw new BusinessException("原密码错误！");
		}
		if (!pwd.equals(newPwd)) {
			throw new BusinessException("两次输入的密码不一致！");
		}
		user.setPassword(DESUtil.encrypt(newPwd, SysConfig.PWD_KEY));
	}

	/**
	 * 重置密码
	 * 
	 * @author WU
	 * @date 2016年12月21日 下午4:01:05
	 * @param user
	 */
	public void resetPwd(UserEntity user) {
		user = this.get(UserEntity.class, user.getId());
		user.setPassword(DESUtil.encrypt(SysConfig.INIT_PWD, SysConfig.PWD_KEY));
	}

	/***
	 * 根据用户名、电话、身份证 验证用户是否存在
	 * 
	 * @author WU
	 * @date 2017年3月8日 上午11:03:43
	 * @param user
	 */
	public void checkUser(UserEntity user) {
		List<Criterion> citList = new ArrayList<Criterion>();
		if (StringUtil.isNotEmpty(user.getPhone())) {
			citList.add(Restrictions.eq("phone", user.getPhone()));
		}
		if (StringUtil.isNotEmpty(user.getCardNo())) {
			citList.add(Restrictions.eq("cardNo", user.getCardNo()));
		}
		if (StringUtil.isNotEmpty(user.getUserName())) {
			citList.add(Restrictions.eq("userName", user.getUserName()));
		}

		QbcQuery qbc = new QbcQuery(UserEntity.class);
		if (user.getId() != null) {
			qbc.add(Restrictions.ne("id", user.getId()));
		}

		if (citList.size() > 0) {
			Criterion[] crit = new Criterion[citList.size()];
			qbc.add(Restrictions.or(citList.toArray(crit)));
		}

		List<UserEntity> uList = this.getList(qbc);
		if (uList.size() == 1) {
			if (StringUtil.isNotEmpty(user.getPhone()) && user.getPhone().equals(uList.get(0).getPhone())) {
				throw new BusinessException("电话号码【" + uList.get(0).getPhone() + "】已被用户【" + uList.get(0).getName() + "】使用！");
			}
			if (StringUtil.isNotEmpty(user.getCardNo()) && user.getCardNo().equals(uList.get(0).getCardNo())) {
				throw new BusinessException("身份证号【" + uList.get(0).getCardNo() + "】已被用户【" + uList.get(0).getName() + "】使用！");
			}
			if (StringUtil.isNotEmpty(user.getUserName()) && user.getUserName().equals(uList.get(0).getUserName())) {
				throw new BusinessException("用户名【" + uList.get(0).getUserName() + "】已被用户【" + uList.get(0).getName() + "】使用！");
			} else {
				throw new BusinessException("用户【" + uList.get(0).getName() + "】已存在！");
			}
		} else if (uList.size() > 1) {
			throw new BusinessException("请检查用户信息的唯一性！");
		}

	}

	/**
	 * 排序
	 * 
	 * @author weiwu
	 * 
	 */
	private class ComparatorUser implements Comparator<FunctionEntity> {
		public int compare(FunctionEntity f1, FunctionEntity f2) {
			return f1.getOrderBy() - f2.getOrderBy();
		}
	}

}
